package com.biz.primus.management.coupon.type.tag;

import com.biz.primus.commodity.vo.backend.CategoryItemVo;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 优惠券可用分类选择标签
 *
 * @author david-liu
 */
@Setter
@Slf4j
public class CouponTypeCategorySelectTag extends TagSupport {
    private static final long serialVersionUID = -3367088141553134603L;

    private Boolean multiSelect;

    private Long selectedCategory;

    private List<Long> selectedCategories;

    @Override
    public int doStartTag() throws JspException {
        List<CategoryItemVo> categoryItemVos = new ArrayList<CategoryItemVo>() {
            {
                add(new CategoryItemVo("1", "分类1"));
                add(new CategoryItemVo("2", "分类2"));
            }
        };

        JspWriter jspWriter = pageContext.getOut();
        if (Objects.nonNull(multiSelect) && multiSelect) {
            categoryItemVos.forEach(vo -> {
                String optionHtmlText;
                if (CollectionUtils.isNotEmpty(selectedCategories) && selectedCategories.contains(Long.valueOf(vo.getId()))) {
                    optionHtmlText = String.format("<option value=\"%s\" selected>%s</option>", vo.getId(), vo.getName());
                } else {
                    optionHtmlText = String.format("<option value=\"%s\">%s</option>", vo.getId(), vo.getName());
                }
                try {
                    jspWriter.println(optionHtmlText);
                } catch (IOException e) {
                    log.error("out jsp error", e);
                }
            });
        } else {
            categoryItemVos.forEach(vo -> {
                String optionHtmlText;
                if (Objects.nonNull(selectedCategory) && Objects.equals(selectedCategory, Long.valueOf(vo.getId()))) {
                    optionHtmlText = String.format("<option value=\"%s\" selected>%s</option>", vo.getId(), vo.getName());
                } else {
                    optionHtmlText = String.format("<option value=\"%s\">%s</option>", vo.getId(), vo.getName());
                }

                try {
                    jspWriter.println(optionHtmlText);
                } catch (IOException e) {
                    log.error("out jsp error", e);
                }
            });
        }
        return super.doStartTag();
    }
}
